package com.hhhn.wk.main.tab4.address;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.main.tab4.address.entity.Address;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.ToastUtils;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.dialog.DelDialog;
import com.hhhn.wk.widget.wkpulltorefreshlayout.BaseRefreshListener;
import com.hhhn.wk.widget.wkpulltorefreshlayout.PullToRefreshLayout;
import com.hhhn.wk.widget.wkpulltorefreshlayout.ViewStatus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/1/7 0007    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 全部收货地址
 * * * * * * * * * * * */
public class AddressAllActivity extends BaseActivity {
    private TextView tv_title;
    private TextView tv_addressAdd;//新增地址
    /*listView*/
    private ListView mLoadListView;
    private PullToRefreshLayout mPullToRefreshLayout;
    public static ArrayList<Address> mArrayList=new ArrayList<Address>();
    private static MyAdaper<Address> mAdapter;
    private int page=1;
    private int refresh = 0;//0 第一次进入  1下拉刷新  2上啦加载
    private boolean isWU = false;
    Context context;
    BaseActivity activity;
    DelDialog confirmDialog=null;
    private LinearLayout ll_empty;
    int type=0;
    Intent intent=null;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mArrayList.size() == 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        loadData();
                    }
                    break;
                case 2:
                    mPullToRefreshLayout.setVisibility(View.GONE);
                    ll_empty.setVisibility(View.VISIBLE);
//                    mPullToRefreshLayout.showView(ViewStatus.EMPTY_STATUS);////空数据
                    dismissLoad();
                    break;
                case 3:
                    mPullToRefreshLayout.setVisibility(View.GONE);
                    ll_empty.setVisibility(View.VISIBLE);
//                    mPullToRefreshLayout.showView(ViewStatus.ERROR_STATUS);////网络错误
                    dismissLoad();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_address_all);
         intent=getIntent();
         type = intent.getIntExtra("type", 1);
    }

    @Override
    protected void initView() {
        context=AddressAllActivity.this;
        activity= this;
        tv_title=  findViewById(R.id.tv_title);
        ll_empty=  findViewById(R.id.ll_empty);
        tv_addressAdd=  findViewById(R.id.tv_addressAdd);
        mLoadListView=  findViewById(R.id.mLoadListView);
        mPullToRefreshLayout =  findViewById(R.id.activity_list);
        mLoadListView.setDivider(new ColorDrawable(getResources().getColor(R.color.colorback)));
//      mLoadListView.setDividerHeight(SysUtils.Dp2Px(getActivity(),2));
    }
    @Override
    protected void initData() {
        tv_title.setText("收货地址");
        getJSON();
    }
    @Override
    protected void initClick() {
        mPullToRefreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                refresh = 1;
                page = 1;
                mArrayList.clear();
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
                isWU = false;
                getJSON();
            }
            @Override
            public void loadMore() {
                if (isWU) {
                    ToastUtils.showShortToast(context,"暂无更多");
                    mPullToRefreshLayout.showView(ViewStatus.CONTENT_END);//暂无更多
                } else {
                    refresh = 2;
                    page++;
                    if (mAdapter!=null){
                        mAdapter.notifyDataSetChanged();
                    }
                    getJSON();
                }
            }
        });
        tv_addressAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(context, AddressAddActivity.class);
                intent.putExtra("title","新增收货地址");
                startActivityForResult(intent,1);
            }
        });
        mLoadListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (type==1){
                        intent.putExtra("shipAddressId",mArrayList.get(i).getId());
                        intent.putExtra("name",mArrayList.get(i).getName());
                        intent.putExtra("phone",mArrayList.get(i).getPhone());
                        intent.putExtra("address",mArrayList.get(i).getCity()+mArrayList.get(i).getAddress());
                        setResult(1,intent);
                        finish();

                    }
            }
        });
    }

    //查询收货地址
    public void getJSON() {
        showLoad();
        RequestParams params = AllPublic.getParams(activity, "/showShipAddress", true);
        params.addParameter("cmUserId",getUser().getUid());/*用户Id*/
        Log.d("查询收货地址", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("查询收货地址：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Address myOrder=null;
                        if (records.length() <  Config.ROWS) {
                            isWU = true;
                        }
                        for (int i=0;i<records.length();i++){
                            myOrder=new Address();
                            JSONObject object = records.getJSONObject(i);
                            String addressId = object.has("id") ? object.getString("id") : "";//id
                            String province = object.has("province") ? object.getString("province") : "";
                            String city = object.has("city") ? object.getString("city") : "";
                            String town = object.has("town") ? object.getString("town") : "";
                            String address = object.has("address") ? object.getString("address") : "";
                            String userName = object.has("shipName") ? object.getString("shipName") : "";//
                            String phone = object.has("shipTel") ? object.getString("shipTel") : "";//
                            int isShow = object.has("isDefault") ? object.getInt("isDefault") : 100902;//100901默认   100902不是默认

                            myOrder.setProvince(province);
                            myOrder.setTown(town);
                            myOrder.setCity(city);
                            myOrder.setDef(isShow);
                            myOrder.setId(addressId);
                            myOrder.setAddress(address);
                            myOrder.setName(userName);
                            myOrder.setPhone(phone);
                            mArrayList.add(myOrder);
                        }
                        handler.sendEmptyMessage(1);
                    }else {
                      toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }
            @Override
            public void onFinished() {

                dismissLoad();
            }
        });
    }
    private void loadData() {
        if (mAdapter==null){
            mAdapter=new MyAdaper<Address>(mArrayList,R.layout.item_address_all) {
                @Override
                public void bindView(ViewHolder holder, final Address obj, final int position) {
                    holder.setText(R.id.tv_name,obj.getName());
                    holder.setText(R.id.tv_phone,obj.getPhone());
                    holder.setText(R.id.tv_address,obj.getProvince()+obj.getCity()+" "+obj.getAddress());
                    //100901默认   100902不是默认
                    if (obj.getDef()==100901){
                        holder.setVisibility(R.id.ll_def,View.VISIBLE);
                    }else {
                        holder.setVisibility(R.id.ll_def,View.GONE);
                    }
                    //编辑
                    holder.setOnClickListener(R.id.ll_up, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(context, AddressAddActivity.class);
                            intent.putExtra("title","编辑收货地址");
                            intent.putExtra("class",mArrayList.get(position));
                            startActivityForResult(intent,1);
                        }
                    });
                    //删除
                    holder.setOnClickListener(R.id.ll_del, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DelDialog.Builder customBuilder = new DelDialog.Builder(context);
                            customBuilder.setPositiveListener(new DelDialog.Builder.ClickListener() {
                                @Override
                                public void click() {
                                    getDel(obj.getId());
                                    confirmDialog.dismiss();
                                }
                            }).setNegativeListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    confirmDialog.dismiss();
                                }
                            });
                            confirmDialog = customBuilder.create();
                            confirmDialog.show();

                        }
                    });
                }
            };
            mLoadListView.setAdapter(mAdapter);
        }else {
            mAdapter.notifyDataSetChanged();
        }
        if (refresh == 1) {
            mPullToRefreshLayout.finishRefresh();//下拉刷新
        } else if (refresh == 2) {
            mPullToRefreshLayout.finishLoadMore();//上啦加载
        }
        mPullToRefreshLayout.setVisibility(View.VISIBLE);
        ll_empty.setVisibility(View.GONE);
       dismissLoad();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mArrayList!=null){
            mArrayList.clear();
        }
        if (mAdapter!=null){
            mAdapter=null;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==1){
            upView();
        }
    }
    private void upView(){
    refresh = 1;
    page = 1;
    mArrayList.clear();
    if (mAdapter != null) {
        mAdapter.notifyDataSetChanged();
    }
    isWU = false;
    getJSON();
}
    //删除收货地址
    public void getDel(String addressId) {
        showLoad();
        RequestParams params = AllPublic.getParams(activity, "/deleteShipAddress", false);
        params.addParameter("cmUserId",getUser().getUid());/*用户Id*/
        params.addParameter("id",addressId);/*地址Id*/
        Log.d("删除收货地址", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("删除收货地址：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        upView();

                    }else {
                                         toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                dismissLoad();
            }
            @Override
            public void onFinished() {
                dismissLoad();
            }
        });
    }}
